package br.diego.tb.unknown;

public class NthNumber 
{

    public static int nth_number(Integer[] v, Integer n) 
    {
    	int highest = Integer.MIN_VALUE;
    	
    	for(Integer number : v)
    	{
    		if(number > highest)
    			highest = number;
    	}
    	
    	bucketSort(v, highest);
        
    	int indexOfNthNumber = v.length - n;
    	
    	System.out.println(v[indexOfNthNumber]);
    	
    	return v[indexOfNthNumber];
    }
    

    private static void bucketSort(Integer[] originalArray, int maxVal) 
    {
       int [] buckets = new int[maxVal+1];
  
       for (int i = 0; i < originalArray.length; i ++)
       {
    	  int actual = originalArray[i];
          
    	  buckets[actual]++;
       }
  
       int originalArrayPos = 0;
       
       for (int value = 0; value < buckets.length; value ++) 
       {
          for (int counterInsideBucket = 0; counterInsideBucket < buckets[value]; counterInsideBucket ++) 
          {
             originalArray[originalArrayPos] = value;
             originalArrayPos ++;
          }
       }

    }
}
